﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Text;
using System.IO;
using System.Drawing.Imaging;
using System.IO.Pipes;

using Domain;
using BusinessTier.Facade.Interface;
using BusinessTier.Facade.Implementation;

//using Svg;

namespace WebMVC.Helpers
{
    public class TextImageGenerator
    {
        private static readonly float DPI_CORRECTION = 1;//4/3f;

        public MemoryStream GetReviewImageThumb(InfoTemplate templ, long productId, string imagePath)
        {
            MemoryStream memStream = new MemoryStream();
            Bitmap bm = GetReviewImage(templ, productId, imagePath);

            bm.Save(memStream, ImageFormat.Png);
            bm.Dispose();
            return memStream;
        }

        public MemoryStream GetImageFromText(string text, System.Drawing.Font font, string color)
        {
            
            MemoryStream memStream = new MemoryStream();
            Bitmap bm = CreateBitmapImage(text, font, Color.FromArgb(Convert.ToInt32(color, 16)));
            
            bm.Save(memStream, ImageFormat.Png);
            bm.Dispose();
            return memStream;
        }

        public Bitmap GetReviewImage(InfoTemplate templ, long productId, string imagePath)
        {
            /*
            IStaticDataService iRepository = new StaticDataService();
            IProductService prodRepository = new ProductService();
            ProductDO product = prodRepository.GetProductById(productId);
            
            Size reviewSize = new Size((int)(templ.Width * DPI_CORRECTION), (int)(templ.Height * DPI_CORRECTION));
            */
            Bitmap bitmap = new Bitmap((int)(templ.Width * 4 / 3f), (int)(templ.Height * 4 / 3f), PixelFormat.Format32bppArgb);
            /*
            Graphics graphics = Graphics.FromImage(bitmap);
            graphics.PageUnit = GraphicsUnit.Point;
            graphics.DrawImage(Image.FromFile(imagePath),new Rectangle(0, 0, reviewSize.Width, reviewSize.Height));
            foreach (var item in templ.Items)
            {
                System.Drawing.Font objFont = new System.Drawing.Font(iRepository.GetFontById(item.FontId).Name, item.Size, 
                    FontStyle.Regular, GraphicsUnit.Point);
                PointF position = GetTextItemPosition(item, reviewSize, GetStringSize(item.Text, objFont,GraphicsUnit.Point));
                DrawStringInPosition(graphics, item.Text, objFont, Color.FromArgb(Convert.ToInt32(item.Color, 16)), position);
            }
            graphics.Flush();
            graphics.Dispose();*/

            return bitmap;
        }


        private PointF GetTextItemPosition(TextItem item, Size rect, Size textSize)
        {
            float x = 0f;

            if (item.Align.Halign.Equals(HalignType.CENTER))
            {
                x = (rect.Width - textSize.Width * 0.965f) / 2F;
            }
            else
            {
                x = item.Align.X * DPI_CORRECTION * 0.965f;
            }

            float y = rect.Height - (item.Align.Y * DPI_CORRECTION) - textSize.Height * 0.62f;// (1 - (item.Align.Y + textHeight) / NATIONAL_BC_VIEW_HEIGHT) * (NATIONAL_BC_HEIGHT - CUT_EXT_LENGTH);
            
            if (item.Align.GrowTo.Equals(GrowToType.MIDDLE))
            {
            }
            else if (item.Align.GrowTo.Equals(GrowToType.LEFT))
            {
                x = x - textSize.Width * 0.965f;
            }
            else if (item.Align.GrowTo.Equals(GrowToType.RIGHT))
            {
                //nothing
            }

            return new PointF(x,y);
        }

        private Size GetStringSize(string text, System.Drawing.Font font, GraphicsUnit unit)
        {
            using (var bitmap = new Bitmap(1, 1))
            {
                int intWidth = 0;
                int intHeight = 0;
                using (var graphics = Graphics.FromImage(bitmap))
                {
                    var ranges = graphics.MeasureCharacterRanges(text, font, RectangleF.Empty, new StringFormat(StringFormat.GenericTypographic));
                    if (ranges.Length > 0)
                    {
                        RectangleF rc = ranges[0].GetBounds(graphics);
                        return new Size((int)(rc.Width + rc.X), (int)(rc.Height + rc.Y));
                    }

                    graphics.PageUnit = unit;
                    var sizef = graphics.MeasureString(text, font,1000,new StringFormat(StringFormat.GenericTypographic));
                    intWidth = (int)sizef.Width;
                    intHeight = (int)sizef.Height;
                    return new Size(intWidth, intHeight);
                }
            }

        }

        private void DrawStringInPosition(Graphics graphics, string text, System.Drawing.Font font, Color color, PointF point)
        {
            graphics.SmoothingMode = SmoothingMode.HighQuality;
            graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
            graphics.CompositingQuality = CompositingQuality.HighQuality;
            graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
            graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

            //TextRenderer.DrawText(graphics, text, font, new Point((int)point.X, (int)point.Y), color,TextFormatFlags.NoClipping);

            GraphicsPath path = new GraphicsPath();
            path.AddString(text, font.FontFamily, (int)FontStyle.Regular, font.Size, new Point(0,0), StringFormat.GenericTypographic);
            var pen = new Pen(new SolidBrush(color));
            pen.Width = 10;
            pen.Alignment = PenAlignment.Outset;
            graphics.DrawPath(pen, path);
            graphics.FillPath(new SolidBrush(Color.FromArgb(Convert.ToInt32("ffaa3333", 16))),path);
            //graphics.DrawString(text, font, new SolidBrush(color), point,new StringFormat(StringFormat.GenericTypographic));
        }

        private Bitmap CreateBitmapImage(string sImageText, System.Drawing.Font font, Color color)
        {

            Size textSize = GetStringSize(sImageText, font,GraphicsUnit.Pixel);
            Bitmap bitmap = new Bitmap(textSize.Width, textSize.Height, PixelFormat.Format32bppArgb);
           
           Graphics graphics = Graphics.FromImage(bitmap);
           graphics.Clear(Color.Transparent);

           DrawStringInPosition(graphics, sImageText, font, color, new PointF(0f,0f));
           graphics.Flush();
           graphics.Dispose();
           return bitmap;
        }

              /* private void testt()
               {
                   SvgDocument doc = new SvgDocument();
                   Svg.SvgText text = new SvgText("dfsdsd");
                   doc.Height = 900;
                   doc.Width = 900;
                   text.X = 0;
                   text.Y = 0;
                   text.Font = new Font("Arial", 20, FontStyle.Regular, GraphicsUnit.Pixel);
           
                   doc.Children.Add(text);
                   FileStream st = new FileStream("c:\\ghghhg.svg",FileMode.OpenOrCreate,FileAccess.ReadWrite);
                   doc.Write(st);


                   //File.WriteAllText("c:\\ggg.svg", doc.ToString());
       //            doc.Content
                   doc.Draw().Save("c:\\hfhfh.png");
               }
        /*
         * private void ScaleImage(){
         * Bitmap scaled = new Bitmap((int)(bitmap.Width * 1.67f), (int)(bitmap.Height * 1.67), PixelFormat.Format32bppArgb);
                  using (Graphics gr = Graphics.FromImage(scaled))
                  {
                       gr.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
                       gr.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                       gr.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None;
                       gr.DrawImage(bitmap, new Rectangle(0, 0, scaled.Width, scaled.Height));
                  }
                  return scaled;
         * }
         * 
               */
    }
}
